﻿var backErrMsg = "很抱歉！暂时无法处理您的请求。此问题已被记录到操作日志，请尽快与我们取得联系。";
$(function() {
    $("input[strformula], textarea[strformula]").each(function() {
        //jQuery.data($('#' + idfun)[0], "fcalcu");
        var ids = $(this).attr("strformula");
        var ipos = ids.indexOf("**");
        var jsdata;
        if (ipos > 0) {
            jsdata = ids.substr(ipos + 2);
            ids = ids.substr(0, ipos);
        }
        var arrid = ids.split(',');
        var binded = true;
        for (var i = 0; i < arrid.length; i++) {
            if (!CalculateControl2(arrid[i], $(this).attr("id")))
                binded = false;
        }
        if (ipos < 0)
            if (binded) $(this).removeAttr("strformula");
        else
            $(this).attr("strformula", jsdata);
    }); 
    bindFormGridEvent();
});

function bindFormGridEvent(sId) {
    $("table[calculator]").each(function() {
        var tbcalstr = $(this).attr("calculator");
        if (!tbcalstr) return;
        var arrcalstr = tbcalstr.split("~!^");
        if (arrcalstr.length % 5 != 0) return;
        var tableId = $(this).attr("id");
        if (sId && tableId.indexOf(sId) < 0) return;
        for (var c = 0; c < arrcalstr.length; c += 5) {
            var colId = arrcalstr[c];
            var sfun = arrcalstr[c + 1];
            var calIds = arrcalstr[c + 2];
            var strPrev = arrcalstr[c + 3];
            var strNex = arrcalstr[c + 4];
            var arrIds = calIds.split("|");
            for (var i = 0; i < arrIds.length; i++) {
                $("textarea[id*='" + arrIds[i] + "'], input[id*='" + arrIds[i] + "']").each(function() {
                    $(this).change(function() {
                        calculateTable(tableId, this);
                    });
                });
            }
            calInfoObj[colId] = [sfun, arrIds, strPrev, strNex];
        }
    });  /**/

    $("tr[isfoot='1'] > td[sfun]").each(function() {
        if (sId) {
            var ptabId = $(this).parents("table").attr("id");
            if (ptabId.indexOf(sId) < 0) return;
        }
        var cid = $(this).attr("cid");
        $("textarea[id*='" + cid + "'], input[id*='" + cid + "']").each(function() {
            $(this).change(function() {
                calculateGridCol(cid);
            });
        });
    });
}

function calculateGridCol(cid) {
    $("tr[isfoot='1'] > td[sfun]").each(function() {
        if (cid != $(this).attr("cid")) return;
        var sfun = $(this).attr("sfun");
        if (sfun == "无") return;
        var cresult = "isNaN";
        var colobjs = $("input[id*='" + cid + "'], td[id*='" + cid + "']");
        var total = colobjs.length;
        colobjs.each(function(index) {
            var curval = "";
            var rwId = $(this).attr("id");
            if (rwId && rwId.indexOf('H') == rwId.length - 1)
                curval = $(this).val();
            else
                curval = $(this).find("div[realval]").attr("realval");
            cresult = GetCaculateRes(sfun, curval, cresult, index + 1, total);
        });
        var ctext = "&nbsp;";
        if (!isNaN(cresult))
            ctext = $(this).attr("sprev") + cresult + $(this).attr("snext");
        $(this).html(ctext);
    });
}

var calInfoObj = {};
function calculateTable(tabId, chObj) {
    var chObjId = $(chObj).attr("id");
    var ptr = $(chObj).parents("tr");
    for (var colId in calInfoObj) {
        var arrcol = calInfoObj[colId];
        var arrIds = arrcol[1];
        var have = false;
        for (var i = 0; i < arrIds.length; i++) {
            if (chObjId.indexOf(arrIds[i]) >= 0) {
                have = true;
                break;
            }
        }
        if (!have) continue;

        var cresult = "isNaN";
        for (var n = 0; n < arrIds.length; n++) {
            var curval = null;
            var rwObj = ptr.find("input[id*='" + arrIds[n] + "']");
            var rwId = rwObj.attr("id");
            if (rwId && rwId.indexOf('H') == rwId.length - 1)
                curval = rwObj.val();
            else {
                var rdObj = ptr.find("td[id*='" + arrIds[n] + "']");
                curval = rdObj.find("div[realval]").attr("realval");
            }
            //if (!curval) continue;
            cresult = GetCaculateRes(arrcol[0], curval, cresult, n + 1, arrIds.length);
        }
        var celltext = "";
        if (!isNaN(cresult)) celltext = arrcol[2] + cresult + arrcol[3];
        var rdObj = ptr.find("td[id*='" + colId + "']");
        if (rdObj && rdObj.length) {
            rdObj.find("div[realval!=undefined]").attr("realval", cresult).html(celltext);
            calculateGridCol(colId);
        } else {
            var rwObj = ptr.find("textarea[id*='" + colId + "']");
            rwObj.val(cresult);
            rwObj.trigger("change");
            rwObj.val(celltext);
            if ($.browser.msie)
                ptr.find("input[id*='" + colId + "']").val(cresult);
        }
    }
}

//数据编辑表计算
function calculateCol(gid, rowIndex, rowData, changes) {
    //if (Object.keys(changes).length < 1) return;
    var ccount = 0;
    for (key in changes) {
        if (changes.hasOwnProperty(key)) {
            ccount++;
            break;
        }
    }
    if (ccount == 0) return;
    var calinfo = jQuery.data($('#' + gid)[0], 'calculate')
    if (!calinfo) return;
    for (var c = 0; c < calinfo.column.length; c++) {
        var col = calinfo.column[c];
        var calfield = col.fname;
        var cresult = "isNaN";
        for (var n = 0; n < col.cols.length; n++) {
            var curval = rowData[col.cols[n]];
            cresult = GetCaculateRes(col.sfun, curval, cresult, n + 1, col.cols.length);
        }
        if (!isNaN(cresult))
            rowData[calfield] = col.sprev + cresult + col.safter;
        else
            rowData[calfield] = "";
        if (c == calinfo.column.length - 1)
            $('#' + gid).datagrid('updateRow', { index: rowIndex, row: rowData });
    }
    var gData = null, foots = null;
    for (var r = 0; r < calinfo.footer.length; r++) {
        var row = calinfo.footer[r];
        for (var c = 0; c < row.length; c++) {
            if (!gData) {
                gData = $('#' + gid).datagrid('getData');
                foots = $('#' + gid).datagrid('getFooterRows')
            }
            var calfd = row[c].fname;
            var cinfo = row[c].info;
            var cresult = "isNaN";
            for (var d = 0; d < gData.rows.length; d++) {
                cresult = GetCaculateRes(cinfo[1], gData.rows[d][calfd], cresult, d + 1, gData.rows.length);
            }
            foots[r][calfd] = cinfo[0] + cresult + cinfo[2];
        }
        if (foots) foots[r]["noformater"] = 1;
    }
    if (foots)
        $('#' + gid).datagrid('reloadFooter', foots);

    CalculateEuiControl(gid);
}

//计算两个值的结果
function GetCaculateRes(funname, newval, prevTotal, curIdx, total) {
    switch (funname) {
        case "求和":
            if (isNaN(prevTotal)) prevTotal = 0;
            if (!newval || isNaN(newval)) newval = 0;
            else newval = parseFloat(newval);
            prevTotal += newval;
            break;
        case "平均值":
            if (isNaN(prevTotal)) prevTotal = 0;
            if (!newval || isNaN(newval)) newval = 0;
            else newval = parseFloat(newval);
            prevTotal += newval;
            if (curIdx == total) prevTotal /= (total * 1.0);
            break;
        case "最大值":
            if (newval && !isNaN(newval)) newval = parseFloat(newval);
            if (isNaN(prevTotal)) prevTotal = newval;
            else if (!isNaN(newval) && prevTotal < newval) prevTotal = newval;
            break;
        case "最小值":
            if (newval && !isNaN(newval)) newval = parseFloat(newval);
            if (isNaN(prevTotal)) prevTotal = newval;
            else if (!isNaN(newval) && prevTotal > newval) prevTotal = newval;
            break;
        default:
            prevTotal = "";
            break;
    }
    return prevTotal;
}

//id需要绑定onblur的id
//cc初始化过的CalculateControl的变量
function CalculateControl2(id, idfun) {
    if (id.indexOf("|") > 0) {
        if (idfun.indexOf("_||") >= 0) {
            var arr = id.split('|');
            $("textarea[id*='" + arr[1] + "'], input[id*='" + arr[1] + "']").each(function() {
                $(this).change(function() {
                    DoCalcute(idfun);
                });
            });
        }
        return false;
    }
    var dyCat = $('#' + id).attr("dytype");
    if (dyCat == 19 || dyCat == 12 || dyCat == 38) return false;
    
    $('#' + id).change(function() {
        DoCalcute(idfun);
    });
    //$(document.getElementById("_||" + id)).change(function() {
    //    DoCalcute(idfun);
    //});
    $("textarea[id*='" + id + "'], input[id*='" + id + "']").each(function() {
        $(this).change(function() {
            DoCalcute(idfun);
        });
    });
    return true;
}

//easyui值改变后，计算用到此控件的控件新值
function CalculateEuiControl(id) {
    $("input[strformula], textarea[strformula]").each(function() {
        var ids = $(this).attr("strformula");
        var idfun = $(this).attr("id");
        var arrid = ids.split(',');
        for (var i = 0; i < arrid.length; i++) {
            if (arrid[i] == id || arrid[i].indexOf(id + "|") == 0) {
                DoCalcute(idfun);
            }
        }
    });
}

function DoCalcute(idfun) {
    var str = "";
    var isDy = true;
    if (idfun.indexOf("_||") >= 0) {
        str = $(document.getElementById(idfun)).attr("strformula");
        isDy = false;
    } else {
        str = jQuery.data($('#' + idfun)[0], "fcalcu");
    }
    var topfun = str;
    var ipos = str.indexOf("**");
    if (ipos > 0) {
        topfun = str.substr(ipos + 2);
    }
    while (true) {
        var n = topfun.indexOf('##');
        if (n < 0) break;
        var afun = topfun.substr(0, n);
        topfun = topfun.substr(n + 2);

        var idx = afun.indexOf(':');
        var cname = afun.substr(0, idx);
        var afun = afun.substr(idx + 1);
        var sval = eval(afun);
        var fres = "'" + sval + "'";
        var d0 = toDate(sval);
        if (isNaN(d0.getDate())) {
            if (!isNaN(sval)) fres = parseFloat(sval);
            else fres = NaN;
        }
        var re = new RegExp(cname, "g");
        topfun = topfun.replace(re, fres);
    }
    while (true) {
        var n = topfun.indexOf('@@');
        if (n < 0) break;
        var afun = topfun.substr(0, n);
        topfun = topfun.substr(n + 2);

        var idx = afun.indexOf(':');
        var fidx = afun.substr(0, idx);
        var afun = afun.substr(idx + 1);
        var sval = eval(afun);
        var fres = parseFloat(sval);
        if (fres != sval)
            fres = "'" + sval + "'";
        topfun = topfun.replace(fidx, fres);//"CalSubFun" + 
    }

    var re = new RegExp("NaN", "gi");
    topfun = topfun.replace(re, 0);
    var lastval = eval(topfun);
    //var flast = parseFloat(lastval);
    //if (flast != lastval) flast = "";
    if (isDy) {
        $("#" + idfun).val(lastval);
    } else {
        var iobj = document.getElementById(idfun);
        iobj.value = lastval;
        $(iobj).trigger("change");
    }
}

//id是需要显示计算结果的控件Id
//用于计算四则运算
//已无用处
function CalculateControl(id) {
    this.cid = id;
    this.paraCtrl = {};
    this.callFun = {};
    this.formula = "";
    this.result = function() {
        for (var rk in this.paraCtrl) {
            this.paraCtrl[rk] = eval(this.paraCtrl[rk]);
            var re = new RegExp("a.paraCtrl." + rk, "g");
            this.formula = this.formula.replace(re , this.paraCtrl[rk]);
        }
        
        var tstr = "cfun = new CalculateFunstr('SUM');cfun.paras.push(\"formCtrlValOp('i2')\");cfun.paras.push(\"formCtrlValOp('i1')\");cfun.result();"
        var test = eval("cfun1 = new CalculateFunstr('SUM');t=\"formCtrlValOp('i2')\";cfun1.paras.push(t);t=\"formCtrlValOp('i1')\";cfun1.paras.push(t);cfun = new CalculateFunstr('SUM');cfun.paras.push(\"formCtrlValOp('i2')\");cfun.paras.push(\"formCtrlValOp('i1')\");cfun1.paras.push('cfun.result()');cfun3 = new CalculateFunstr('AVG');cfun3.paras.push(\"formCtrlValOp('i2')\");cfun3.paras.push(\"formCtrlValOp('i1')\");cfun1.paras.push('cfun3.result()');cfun1.result();")//cfun1.paras.push(\""+ tstr +"\");
        return eval(this.formula);
    };

    
    if (id == "DyInput1") {
        var str = jQuery.data($('#DyInput1')[0], "fcalcu");
        var f = eval(str);
        //alert(f.result);
    }
}

function toDate(ds) {
    if (ds && ds.indexOf(' ') > 0) {
        //ds = ds.replace(/ /g, ',');
        //var sarr = ds.split(":");
        //ds = sarr[0];
        //if (sarr.length > 1) ds += ":" + sarr[1];
        //if (sarr.length > 2) ds += ":" + sarr[2];
    } else {
        ds += " 0:0:0";
    }
    if(ds) ds = ds.replace(/-/g, '/');
    //alert(ds);
    return new Date(ds);
}

//用于计算多个参数的函数，目前有max，min，avg，sum，LISTSUMALL，DATEDIFF，DATEADD
function CalculateFunstr(fun) {
    this.functionname = "";
    switch (fun.toLowerCase()) {
        case "max":
            this.functionname = "最大值";
            break;
        case "min":
            this.functionname = "最小值";
            break;
        case "avg":
            this.functionname = "平均值";
            break;
        case "sum":
            this.functionname = "求和";
            break;
        default:
            this.functionname = fun.toLowerCase();
            break;
    }
    this.paras = [];
    this.result = function() {
        var res = "";
        var ptype = GetParsType(this.paras);
        if (ptype != 0) {
            var nparas = GetRealDatas(this.paras, ptype, this.functionname);
            if (ptype == 1)
                this.paras = nparas;
            else
                return nparas;
        }
        switch (this.functionname) {
            case "dateadd":
                var d = toDate(this.paras[0]);
                var ds = this.paras[1].toLowerCase();
                var year = d.getFullYear(), month = d.getMonth(), date = d.getDate(), hour = d.getHours(), minute = d.getMinutes(), seconds = d.getSeconds();
                if (ds) {
                    ds = ds.replace("d", " * 24 * 60 + ");
                    ds = ds.replace("h", " * 60 + ");
                    ds = ds.replace("m", " + ");
                    ds += "0";
                    minute += eval(ds);
                }
                var nd = new Date(year, month, date, hour, minute, seconds);
                res = this.paras[2];
                if (res) {
                    var re = new RegExp("y", "gi");
                    res = res.replace(re, nd.getFullYear());
                    re = new RegExp("n", "gi");
                    res = res.replace(re, nd.getMonth() + 1);
                    re = new RegExp("d", "gi");
                    res = res.replace(re, nd.getDate());
                    re = new RegExp("h", "gi");
                    res = res.replace(re, nd.getHours());
                    re = new RegExp("m", "gi");
                    res = res.replace(re, nd.getMinutes());
                    re = new RegExp("s", "gi");
                    res = res.replace(re, nd.getSeconds());
                } else {
                    res = nd.getTime() / 1000;
                }
                break;
            case "datediff":
                var d0 = toDate(this.paras[0]);
                var d1 = toDate(this.paras[1]);
                d0 = d0.getTime();
                d1 = d1.getTime();
                if (!isNaN(d0) && !isNaN(d1)) {
                    var ms = Math.abs(d0 - d1);  //时间差的毫秒数
                    res = this.paras[2];
                    if (res) {
                        if (res.indexOf('d') >= 0 || res.indexOf('D') >= 0) {
                            var day = Math.floor(ms / (24 * 3600 * 1000));
                            ms = ms % (24 * 3600 * 1000);
                            var re = new RegExp("d", "gi");
                            res = res.replace(re, day);
                        }
                        if (res.indexOf('h') >= 0 || res.indexOf('H') >= 0) {
                            var hour = Math.floor(ms / (3600 * 1000));
                            ms = ms % (3600 * 1000);
                            var re = new RegExp("h", "gi");
                            res = res.replace(re, hour);
                        }
                        if (res.indexOf('m') >= 0 || res.indexOf('M') >= 0) {
                            var minute = Math.floor(ms / (60 * 1000));
                            ms = ms % (60 * 1000);
                            var re = new RegExp("m", "gi");
                            res = res.replace(re, minute);
                        }
                    } else {
                        res = ms / 1000;
                    }
                }
                break;
            default:
                var prevTotal = "isNaN";
                for (var rk = 0; rk < this.paras.length; rk++) {
                    try {
                        this.paras[rk] = eval(this.paras[rk]);
                    } catch (e) {
                    }
                    prevTotal = GetCaculateRes(this.functionname, this.paras[rk], prevTotal, rk + 1, this.paras.length);
                }
                res = prevTotal;
                break;
        }
        return res;
    };
}

function GetParsType(oldparas){
    if (oldparas.length >= 4) {
        if(oldparas[0] == "dgcol" || oldparas[0] == "tbcol" || oldparas[0] == "formcol"){
            if(oldparas[3] == 1) return 2;//列所有数据和
            else return 1;//所有列当前页和
        }
    }
    return 0;//常用函数
}
function GetRealDatas(oldparas, type) {
    var gid = oldparas[1];
    var citem = oldparas[2];
    var gData = null;
    if (type == 2) {
        //all data
        var colresult = null;
        var sendObj = {};
        sendObj.iid = $("#hIidPlus").val(); //"<%=IidPlus%>";
        sendObj.fid = $("#hfid").val(); //"<%=fid%>";
        sendObj.action = "ColumnResult";
        sendObj.objid = gid;
        sendObj.input_index = $("#hinput_index").val(); //"<%=input_index%>";
        sendObj.keyword = $("#" + gid).attr("dskeys");
        sendObj.table = oldparas[4];
        sendObj.field = citem;
        $.ajax({
            url: ((oldparas[0] == "formcol") ? '../DynamicForm/GetData.aspx' : 'GetData.aspx'),
            type: 'Post',
            async: false,
            cache: false,
            data: sendObj,
            dataType: 'text',
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                alert("取得列数据时发生远程请求错误！");
            },
            success: function(result) {
                if (result.indexOf(backErrMsg) > 0) {
                    alert("请求错误！请联系管理员查看日志。");
                    result = 0;
                }
                colresult = result;
            }
        });
        return colresult;
    } else {
        if (oldparas[0] == "dgcol") {
            gData = $('#' + gid).datagrid('getData');
        } else if (oldparas[0] == 'tbcol') {
            gData = jQuery.data($("#" + gid)[0], "datas");
        }
    }
    var nparas = [];
    if (oldparas[0] == "formcol") {
        var bInput = false;
        $("input[id*='" + citem + "']").each(function() {
            nparas.push(this.value);
            bInput = true;
        });
        if (!bInput) {
            $("td[id*='" + citem + "'][norow!=1]").each(function() {
                var rspan = $(this).attr("rowspan");
                var obj = $(this).find("div[realval!=undefined]");
                var oneval = "";
                if (obj.length > 0) oneval = obj.attr("realval");
                for (var i = 0; i < rspan; i++)
                    nparas.push(oneval);
            });
        }
    } else {
        for (var d = 0; d < gData.rows.length; d++) {
            var dval = gData.rows[d][citem];
            nparas.push(dval);
        }
    }
    return nparas;
}